<template>
  <div class="util-box">
    <a-popover placement="top">
      <template #content>
        <div class="emoji-list">
          <span class="emoji-item hover" v-for="(item, index) in emojis" :key="index" @click="onChoose(index)">
            {{ item }}
          </span>
        </div>
      </template>
      <SvgIcon name="smell" class="hover" :class-value="{ width: '26px', height: '26px' }"></SvgIcon>
    </a-popover>
    <a-upload :file-list="fileList" :before-upload="beforeUpload" listType="picture" :showUploadList="false"
      :custom-request="customRequest">
      <SvgIcon name="fileOpen" class="hover" :class-value="{ width: '26px', height: '26px' }"></SvgIcon>
    </a-upload>
  </div>
</template>
<script lang='ts' setup>
import SvgIcon from '@/components/SvgIcon/index.vue';
import { message } from 'ant-design-vue';
import { ref } from 'vue';

const emit = defineEmits(["getEmogi", "getImg"]);
const fileList = ref<any[]>([]);
const emojis = [
  '😀', '😄', '😅', '🤣', '😂', '😉', '😊', '😍', '😘', '😜',
  '😝', '😏', '😒', '🙄', '😔', '😴', '😷', '🤮', '🥵', '😎',
  '😮', '😰', '😭', '😱', '😩', '😡', '💀', '👽', '🤓', '🥳',
  '😺', '😹', '😻', '🤚', '💩', '👍', '👎', '👏', '🙏', '💪'
]
const emojiList = ref<{ text: string }[]>(emojis.map(item => {
  return {
    text: item
  }
}))

/**
 * 上传文件前的钩子
 * @param file 
 */
const beforeUpload = (file: File) => {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error({
      content: "只能上传JPG或PNG文件!"
    });
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error({
      content: "图片大小需小于2MB!"
    });
    return false;
  }
  return isJpgOrPng && isLt2M;
}

/**
 * 通过覆盖默认的上传行为，可以自定义自己的上传实现
 */
const customRequest = (option: any) => {
  const formData = new FormData();
  formData.append("files[]", option.file);
  const reader = new FileReader();
  reader.readAsDataURL(option.file);
  reader.onloadend = function (e: ProgressEvent) {
    let obj: any = (e.target as any).result;
    emit("getImg", obj)
  };
}

/**
 * 选择了表情包
 * @param index 索引
 */
const onChoose = (index: number) => {
  emit('getEmogi', emojiList.value[index].text);
}

</script>
<style lang='less' rel='stylesheet/less' scoped>
.util-box {
  height: 40px;


}

.emoji-list {
  width: 360px;

  .emoji-item {
    width: 30px;
    display: inline-block;
    height: 30px;
    text-align: center;
    line-height: 26px;
    border: 1px solid #e8e8e8;
  }
}

.hover {
  cursor: pointer;
}
</style>